Page({
    data: {
      voteID: '', // 当前投票的ID
      dsecImgUrl:"",//描述图片
      haveDsecImg:true,
      imgUrl:'../../imgs/addImg.png',//自定义分享图
      displayOption:0,//是否显示票数
      shuffleOptions:false,//是否打乱顺序
      needPersonalInformation:false,//是否需要个人信息
      isPictureVote:false,//是否为图文投票
      optionImgList: [],//选项图
      voteCreate:"",//创建日期
      shareGroupImgUrl:"../../imgs/share.png",//icon
      shareImgUrl:"",
      multiple: false, // 当前投票的类型，多选
      onlyGroupMember:0,//只允许群成员投票
      voteTitle: '', // 当前投票的标题
      voteDesc: '11111111', // 当前投票的补充描述
      optionList: [], // 当前投票的选项列表
      endDate: '', // 当前投票的截止日期
      isAnonymous: false, // 当前投票是否匿名
      isExpired: false, // 当前投票是否已过期
      pickedOption: [], // 当前用户选择的选项
      optionStatus: [],// 每个选项的投票情况
      optionRadio:[] ,//每个选项所占的比例
      totalVoteCount:0,// 总投票数量
      alreadyVoted:false, // 当前用户是否已经投票
      optionDesc:'',
      optionidList:[],
      voteStatus:[],
      buttonDisable:false,
      userImgUrl:"../../imgs/login.png",//用户头像
      nickname:"未登录",
      isLogin:false,
      voteAvatarUrls:[], //所有参与到该投票的用户头像,
      textName:"",   //输入的姓名
      textPhone:"",  //输入的手机号码
      isInput:false,  //是否输入了个人信息
      isShowModal:false, //是否显示过弹窗
      regJudge: false,
      optionsMinNum:1,
      optionsMaxNum: 2,
      createrOpenId:"",//发起人的openid
      isCreater: false,
      blockHeight:0,//区块高度
      transactionId:0,//交易ID
      CreatedOrJoined:1,//从创建页面进入or从参与页面进入
    },
    onLoad(options) {
      const voteID = options.voteID // 通过页面路径参数获取投票ID
      const CreatedOrJoined = options.CreatedOrJoined
      console.log('voteID',voteID)
      console.log('CreatedOrJoined',CreatedOrJoined)
      this.setData({
        voteID:voteID,
        CreatedOrJoined:CreatedOrJoined
      })
      this.getVoteStatusFromBlockchain(voteID)
      this.getVoteDataFromBlockchain(voteID)
    //   this.getVoteStatusFromBlockchainAndLocal(this.data.voteID) 
    //   this.getVoteDataFromBlockchainAndLocal(this.data.voteID) 
      this.checkLogin()
      this.queryBlockInfo(this.data.voteID)
      // if (wx.getStorageSync('userid') != ''){
      //   //console.log(userid)
      //   let userid = wx.getStorageSync('userid')
      //     this.setData({
      //       userId: userid
      //     })
      // }
      wx.showShareMenu({
        withShareTicket: true
      })
    },
    onPullDownRefresh: function () {
      this.getVoteStatusFromBlockchain(voteID)
      this.getVoteDataFromBlockchain(voteID)
    //   this.getVoteStatusFromBlockchainAndLocal(this.data.voteID) // 从服务端获取是否已经投票
    //   this.getVoteDataFromBlockchainAndLocal(this.data.voteID) // 从服务端获取投票情况
    },
    checkExpired(endDate) {
      const now = new Date();
      const endDateArray = endDate[0].split('-') // 将字符串分割成字符数组，分隔符为-
      const endYear = Number(endDateArray[0]) // 取字符数组中的年份，并将数据类型转换为number
      const endMonth = Number(endDateArray[1]) // 取字符数组中的月份，并将数据类型转换为number
      const endDay = Number(endDateArray[2]) // 取字符数组中的日期，并将数据类型转换为number
  
      const endDateArray2 = endDate[1].split(':') 
      const endHour = Number(endDateArray2[0]) 
      const endMinute = Number(endDateArray2[1]) 
      const endSecond = Number(endDateArray2[2]) 
  
      const time = new Date(endYear,endMonth-1,endDay,endHour,endMinute,endSecond);
      console.log('now',now)
      console.log('time',time)
      if(now>time){
        console.log('过期啦')
        return true;
      }else{
        console.log('没过期啦')
        return false;
      }
    },
    onPickOption(e) {
      if (this.data.multiple) {
        this.setData({
          pickedOption: e.detail.value// checkbox-group获取的值是一个array
        })
      } else {
        // 更新选择的选项（单选投票）
        this.setData({
          pickedOption: [ // 为了与多选投票统一，使用数组保存选择的选项
            e.detail.value // radio-group获取的值是一个string
          ]
        })
      }
    },
  
    onTapVote() {
      let that = this 
            //console.log(this.data.buttonDisable)
      if(that.data.isLogin===false){
        wx.login({
          success: function(login_res) {
          that.setData({
              code:login_res.code,
              userid:login_res.userid
          })
          wx.setStorageSync('code', login_res.code)
          wx.setStorageSync('userid', login_res.userid)
          }
        })
        wx.showModal({
          cancelColor: 'cancelColor',
          title: '您还未登录',
          content: '请先登录再进行操作',
          confirmText:'立即登录',
          cancelText:'暂不登录',
          showCancel: false,
          success:function(res){
            if(res.confirm){
              that.userLogin()
              that.checkLogin()
            }
          }
        })
        return
      }  
      //当已经显示过弹窗且输入了个人信息以后，这个情况才会过掉
      if((that.data.isShowModal===false) && (that.data.isInput===false) &&(that.data.needPersonalInformation===true)){
        that.setData({
          isShowModal:true  
        })
        return
      }
  
      //const msg = this.checkFormValid() //对选择的内容进行检查
      //单选
      if( that.data.multiple === false){
        if ( that.data.pickedOption==null) {        
          wx.showModal({
            cancelColor: 'cancelColor',
            title:'提示',
            content:'最少需要选择1个选项',
            showCancel:false,
            confirmText:'我知道了',
          })
          return
        }
      }
      //多选
      else{
        if( that.data.pickedOption!=null){
          let num =  that.data.pickedOption.length
          let content = '请选择' +  that.data.optionsMinNum + '~' +  that.data.optionsMaxNum + '个选项'
          if(num <  that.data.optionsMinNum || num >  that.data.optionsMaxNum){
            wx.showModal({
              cancelColor: 'cancelColor',
              title:'提示',
              content:content,
              confirmText:'我知道了',
              showCancel:false
            })
            return 
          }
  
        }
        else{
          let content = '请选择' +  that.data.optionsMinNum + '~' +  that.data.optionsMaxNum + '个选项'
          wx.showModal({
            cancelColor: 'cancelColor',
            title:'提示',
            content:content,
            confirmText:'我知道了',
            showCancel:false
          })
          return 
        }
  
        
      }
  
  
      //若已经逾期，则不能投票出去
      const endDateArray =  that.data.endDate.split(' ') // 将字符串分割成字符数组，分隔符为-
      if( that.checkExpired(endDateArray)){
        wx.showToast({
          title: '已逾期',
          icon:'error',
          duration: 2000
        })
        return     
      }
  
  
       // 校验通过时后面的内容才会被执行
       if(wx.getStorageSync('code') == '') {
        wx.login({
          success: function(login_res) {
            that.setData({
              code:login_res.code
            })
            wx.setStorageSync('code', login_res.code)
          }
        })
      }
        const _this =  that // 在API接口中的函数中，this会被改变，因此需要提前获取this的值到_this中
        const now = new Date()
        const nowYear = now.getFullYear()
        const nowMonth = (now.getMonth() + 1)>=10?now.getMonth() + 1:'0'+(now.getMonth() + 1)
        const nowDay = now.getDate()>=10?now.getDate():'0'+now.getDate()
        let pickoptionidlist = []       //选中选项的id列表
        let optionDescList = []        //选中选项列表对应的理由列表
        let votestatus = []
        for (let i=0;i<_this.data.optionList.length;i++) {
          votestatus.push(false)
        }
        for (let i=0;i<_this.data.pickedOption.length;i++) {
          let index = _this.data.pickedOption[i];
          votestatus[index] = true
          pickoptionidlist.push(_this.data.optionidList[index])
          console.log("_this.data.optionidList",_this.data.optionidList)
          console.log("_this.data.optionList",_this.data.optionList)
          optionDescList.push(_this.data.optionList[index][2])
        }
        console.log("optionDescList:",optionDescList)

        _this.setData({
          voteStatus:votestatus,
          buttonDisable:true
        })
        wx.showLoading({
          title: '加载中',
          mask:true
        })
        wx.request({
          //url: 'https://www.intohash.com/vote_backend/vote_user/vote',
          url: 'http://localhost:8010/vote_backend/vote_user/vote',
          method:"POST",
          data: {
            "currentTime":nowYear+'-'+nowMonth+'-'+nowDay,
            "optionList": pickoptionidlist,
            "userId": wx.getStorageSync('userid'),
            "voteId": _this.data.voteID,
            "optionDescList":optionDescList     //传输选项理由列表的字段
          },
          success:function(res) {
            console.log('投票成功')
            console.log(res)
            _this.getVoteStatusFromBlockchain(_this.data.voteID) // 从服务端获取是否已经投票
            _this.getVoteDataFromBlockchain(_this.data.voteID) // 从服务端获取投票情况
     
            wx.hideLoading()
  
            _this.queryBlockInfo(_this.data.voteID)
          },
          fail:function(res) {
            
            wx.hideLoading()
       
            console.log(res)
            wx.showToast({
              title: '投票失败',
              icon: 'none'
            })
          }
        })
      
    }, 
  
    getVoteStatusFromBlockchain(voteID) {
      let that = this
      wx.request({
        // url: 'https://www.intohash.com/vote_backend/vote_user/queryHaveVoted/'+wx.getStorageSync('userid')+'/'+this.data.voteID,
        url: 'http://localhost:8010/vote_backend/vote_user/queryHaveVoted/'+wx.getStorageSync('userid')+'/'+this.data.voteID,
        method:'GET',
        success:function (res) {
          console.log('查询投票')
          console.log(res)  // 控制台输出服务端返回的结果
          that.setData({
            alreadyVoted:res.data.data.haveVoted,
            pickedOption:res.data.data.userOptions
          })
        },
        fail: function(res) {
          console.error(res)  // 如果出现异常，控制台输出异常详情
          wx.showToast({  // 调用提示框API提示用户获取数据失败
            title: '获取投票数据失败',
            icon: 'none'
          })
        }
      })
    },
     getVoteDataFromBlockchain(voteID) {
      let that = this
      wx.request({
        //url: 'https://www.intohash.com/vote_backend/vote/queryVoteInfo/'+this.data.voteID,
        url: 'http://localhost:8010/vote_backend/vote/queryVoteInfo/'+this.data.voteID,
        method:'GET',
        success:function(res) {
          const ret = res.data.data
          console.log('投票信息')
          console.log(ret)
          console.log(that.data)
          const endDateArray = ret.rule.endDate.split(' ') // 将字符串分割成字符数组，分隔符为-
          const isExpired = that.checkExpired(endDateArray) // 检查投票是否已经过期
          let optionlist = []          //记录选项内容、选项的图片url、选项的理由
          let optionstatus = []        //记录每个选项的票数
          let optionidlist = []        //记录每个选项的id
          let voteOptionList = res.data.data.optionList   //保存添加投票时输入的所有选项列表
          let  totalvotecount  = 0     //记录总的投票数目
          let optionradio = []
          for (let i=0; i<ret.optionList.length; i++) {
            optionlist.push([voteOptionList[i].optionStr,voteOptionList[i].imgUrl,voteOptionList[i].optionDesc])
            optionstatus.push(ret.optionList[i].count)   
            totalvotecount+=parseInt(ret.optionList[i].count)
            optionidlist.push(ret.optionList[i].optionId)
          }
          for (let i=0; i<ret.optionList.length; i++) {
            optionradio.push(parseInt(parseInt(ret.optionList[i].count)/totalvotecount*100))
          }
          let voteShareImgurl = ret.shareImgUrl;
          if (voteShareImgurl == '../../imgs/addImg.png') {
            voteShareImgurl = ''
          }
          that.setData({
            voteTitle:ret.title,
            voteDesc:ret.voteDesc,
            endDate:ret.rule.endDate,
            multiple:ret.rule.type?true:false,
            needPersonalInformation:ret.rule.needPersonalInformation?true:false,
            shuffleOptions:ret.rule.shuffleOptions,
            displayOption:ret.rule.displayOption,
            voteCreate:ret.voteCreate,
            isExpired:isExpired,
            optionList:optionlist,
            totalVoteCount:totalvotecount,
            optionStatus:optionstatus,
            optionidList:optionidlist,
            onlyGroupMember:ret.rule.onlyGroupMember,
            dsecImgUrl:ret.dsecImgUrl,
            isPictureVote: ret.rule.voteType,
            shareImgUrl:voteShareImgurl,
            isAnonymous:ret.rule.isAnonymous,
            voteAvatarUrls:ret.voteAvatarUrls,
            optionsMinNum: ret.leastLimit,
            optionsMaxNum: ret.mostLimit,
            optionRadio:optionradio,
            createrOpenId:ret.openId
          })
          if(that.data.dsecImgUrl==="../../imgs/addDescImg.png"){
          that.setData({
            haveDsecImg:false
          })
        }
        if(that.data.alreadyVoted===false) that.change(that)   //用来改变顺序的函数
        if(isExpired){
          that.setData({
            alreadyVoted:true
          })
        }
        if(that.data.alreadyVoted===true){
          that.setData({
            textName:wx.getStorageSync('name'),
            textPhone:wx.getStorageSync('Phone'),
            isInput:wx.getStorageSync('isInput')
          })
        }
        if(that.data.createrOpenId===wx.getStorageSync('userid')){
          that.setData({
            isCreater:true
          })
        }
        },
        fail:function(res) {
        }
  
      })
      //return that.data.allowGroupVote
    },
    onShareAppMessage: function (res) {
      console.log("转发");
      return {
      title: '邀请你参与投票',
      path: '/pages/vote/vote?voteID=' + this.data.voteID,
      imageUrl: this.data.shareImgUrl,
      success(res){
        console.log('成功')
        if(that.data.onlyGroupMember!=0) wx.hideShareMenu()
      }
      }
    },
    previewImage() {
      wx.previewImage({
        urls: [this.data.dsecImgUrl],
      })
  },
    change(that){
      
      // console.log('change')
      // console.log(that)
      let optlist=that.data.optionList
      console.log(optlist)
      if(that.data.shuffleOptions===1){
        var len = optlist.length
        for (var i = 0; i < len - 1; i++) {
            var index = parseInt(Math.random() * (len - i));
            var temp1 = optlist[index];
            optlist[index] = optlist[len - i - 1];
            optlist[len - i - 1] = temp1;
            
        }
        // console.log(optlist)
        that.setData({
          optionList:optlist,
        })
      }
    },
    getVoteStatusFromBlockchainAndLocal(voteID) {
      let that = this
      wx.request({
        // url: 'https://www.intohash.com/vote_backend/vote_user/queryHaveVoted/'+wx.getStorageSync('userid')+'/'+this.data.voteID,
        url: 'http://localhost:8010/vote_backend/vote_user/queryHaveVoted/'+wx.getStorageSync('userid')+'/'+this.data.voteID,
        method:'GET',
        success:function (res) {
          console.log('查询本地投票')
          that.setData({
            alreadyVoted:res.data.data.haveVoted,
          })
  
        },
        fail: function(res) {
          console.error(res)  // 如果出现异常，控制台输出异常详情
          wx.showToast({  // 调用提示框API提示用户获取数据失败
            title: '获取投票数据失败',
            icon: 'none'
          })
        }
      })
    },
    getVoteDataFromBlockchainAndLocal(voteID) {
      let that = this
      wx.request({
        // url: 'https://www.intohash.com/vote_backend/vote/queryVoteInfo/'+this.data.voteID,
        url: 'http://localhost:8010/vote_backend/vote/queryVoteInfo/'+this.data.voteID,
        method:'GET',
        success:function(res) {
          const ret = res.data.data
          console.log('本地投票信息')
          console.log(ret)
          let optionstatus = []
          let totalvotecount = 0
          let optionradio = []
          for (let i=0; i<ret.optionList.length; i++) {
            optionstatus.push(ret.optionList[i].count)
            totalvotecount+=parseInt(ret.optionList[i].count)
          }
          for (let i=0; i<ret.optionList.length; i++) {
            optionradio.push(parseInt(parseInt(ret.optionList[i].count)/totalvotecount*100))
          }
          that.setData({
            totalVoteCount:totalvotecount,
            optionStatus:optionstatus,
            voteAvatarUrls:ret.voteAvatarUrls,
            optionRadio:optionradio
          })
          if(that.data.dsecImgUrl==="../../imgs/addDescImg.png"){
          that.setData({
            haveDsecImg:false
          })
        }
        if(that.data.alreadyVoted===false) that.change(that)
  
        console.log(that.data)
        },
  
        fail:function(res) {
        }
  
      })
    },
    checkLogin:function(){
      if (wx.getStorageSync('userinfo') != '') {
        //console.log(userinfo)
        let userinfo = wx.getStorageSync('userinfo')
          this.setData({
            nickname: userinfo.nickName,
            userImgUrl: userinfo.avatarUrl,
            isLogin:true
          })
      }
      else{
        this.setData({
          isLogin:false
        })
      }
    },
    userLogin : function() {
      if (wx.getStorageSync('userid') == '') {
          let that = this
          wx.getUserProfile({
              desc:'请求用户授权',
              success: function(info_res) {
                console.log(info_res)
                let userinfo = info_res.userInfo
                wx.setStorageSync('userinfo', userinfo)
                that.setData({
                  nickname: userinfo.nickName,
                  userImgUrl: userinfo.avatarUrl,
                  isLogin:true
              })
                // 2. 小程序通过wx.request()发送code到开发者服务器
                wx.request({
                  //url: 'https://www.intohash.com/vote_backend/user/login',
                  url: 'http://localhost:8010/vote_backend/user/login',
                  method: 'POST',
                  data: {
                    authTyoe: 1 ,
                    code: wx.getStorageSync('code'), //临时登录凭证
                    encrypteData: info_res.encryptedData, //用户敏感信息
                    iv: info_res.iv, //解密算法的向量
                    rawData: info_res.rawData, //用户非敏感信息
                    signature: info_res.signature //签名   
                  },
                  success: function(res) {
                    console.log('验证成功')
                    console.log(res)
                    wx.setStorageSync('skey', res.data.data.sKey)
                    wx.setStorageSync('userid', res.data.data.openid)
                    wx.request({
                      //url: 'https://www.intohash.com/vote_backend/user/qrCode/'+res.data.data.openid,
                      url: 'http://localhost:8010/vote_backend/user/qrCode/'+res.data.data.openid,
                      method: "GET",
                      success:function(res) {
                        wx.setStorageSync('qrCodeUrl', res.data.data)
                        that.setData({
                          qrCodeUrl: res.data.data
                        })
                      }
                    })
                    wx.redirectTo({       // 自动跳转到参与投票页面
                      url: '/pages/vote/vote?voteID=' + that.data.voteID,
                    })
                  },
                  fail: function(error) {
                    //调用服务端登录接口失败
                    wx.showToast({
                      title: '登陆失败!',
                      duration: 2000,
                    })
                    console.log(error);
                  }
                })
              }
            })
      }
    },
  
    wish_put1:function(e){
      this.setData({
        textName:e.detail.value
      })
      console.log('textname',this.data.textName)
    },
    wish_put2:function(e){
      this.setData({
        textPhone:e.detail.value
      })
      console.log('text',this.data.textPhone)
    },
    confirm(){
      let curPhone = this.data.textPhone
      console.log("qqq")
      console.log(curPhone)
      if (!(/^1[34578]\d{9}$/.test(curPhone))) {
        wx.showToast({
               title: '手机号格式有误',
              icon:'error',
               duration: 2000
              })
        this.setData({
         regJudge: false
        })
        if (curPhone.length >= 11) {
              wx.showToast({
               title: '手机号格式有误',
               icon:'error',
               duration: 2000
              })
             }
            } else {
             this.setData({
            regJudge: true
             })}
             console.log('验证成功', this.data.regJudge)
        if( this.data.regJudge===true){
          this.setData({
            isInput:true,
            isShowModal:false,
          })
          wx.setStorageSync('name', this.data.textName)
          wx.setStorageSync('Phone', this.data.textPhone)
          wx.setStorageSync('isInput', this.data.isInput)
        }
  
    },
    back(){
      //如果点击了返回，就当还没有显示过弹窗 
      this.setData({
        isShowModal:false,
      })
    },
    queryBlockInfo(voteid){
      console.log("voteid",voteid)
      console.log("voteID",this.data.voteID)
      let that = this
      wx.request({
        // url: 'https://www.intohash.com/vote_backend/vote/queryVoteDetail/'+that.data.voteID,
        url: 'http://localhost:8010/vote_backend/vote/queryVoteDetail/'+that.data.voteID,
        method:'GET',
        data: {
          "userId": wx.getStorageSync('userid'),
          "voteId": that.data.voteID
        },
        success:function (res) {
          console.log('查询区块链信息成功')
          console.log(res)  // 控制台输出服务端返回的结果
          that.setData({
            blockHeight:res.data.data.voteDetails[0].voteBlockChain.blockHeight,
            transactionId:res.data.data.voteDetails[0].voteBlockChain.transactionId
          })
          wx.setStorageSync('blockHeight', res.data.data.voteDetails[0].voteBlockChain.blockHeight)
          wx.setStorageSync('transactionId', res.data.data.voteDetails[0].voteBlockChain.transactionId)
        },
        fail:function(res) {
          console.log(res)
          wx.showToast({
            title: '查询区块链信息失败',
            icon: 'none'
          })
          }
      })
    },
    inputOptionDesc(e){
        let pickedOption = this.data.pickedOption
        let index = e.target.dataset.index  //获取输入框的索引
        console.log(index)
        this.data.optionList[index][2] = e.detail.value
        console.log(this.data.optionList)
    },
  
  })